package org.pc2r.network;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;

import org.pc2r.protocole.RequestBuilder;
import org.pc2r.protocole.message.Message;
import org.pc2r.util.SystemUtil;

public class SocketReadWriter implements Closeable {

	private Socket socket;

	public SocketReadWriter(Socket socket) {
		this.socket = socket;
	}

	public void write(Message request) throws IOException {
		write(request.toString());
	}

	public void write(String request) throws IOException {
		OutputStream outputStream = socket.getOutputStream();
		outputStream.write(request.getBytes());
		outputStream.flush();
	}

	public String read() throws IOException {
		return read(false);
	}

	public String read(boolean appendEnd) throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				socket.getInputStream()));
		String readLine = reader.readLine();
		return (appendEnd) ? readLine + RequestBuilder.END : readLine;
	}

	@Override
	public void close() {
		SystemUtil.close(socket);
	}

}
